package myJs.admin.companyMemeberManage

import myJs.Implicits._
import myJs.api.Api
import myJs.common.InputInlineCp
import myJs.cps.Style
import myJs.myPkg.jquery.$
import myJs.myPkg._
import myJs.myPkg.reactBootstrap.Modal
import myJs.myPkg.reactHookForm.{ReactHookForm, RegisterOptions, UseFormOptions, ValidationValueMessage}
import myJs.tool.Tool
import org.scalajs.dom.{FormData, html}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.core.facade.React
import slinky.web.html._

import scala.concurrent.{Future, Promise}
import scala.scalajs.js
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo

import scala.scalajs.js.timers.SetTimeoutHandle
import scala.scalajs.js.{JSON, |}

/**
 * Created by yz on 21/1/2022
 */
@react object AddCp {

  import Pojo.companyMember._

  case class Props(refreshTableB: () => Future[Unit], show: Boolean = false, showChange: Boolean => Unit)

  val component = FunctionalComponent[Props] { props =>

    val (account, setAccount) = useState("")
    val (password, setPassword) = useState("")
    val (companyName, setCompanyName) = useState("")
    val (delayTimer, setDelayTimer) = useState(null: SetTimeoutHandle)

    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange"))

    object FTool {

      def handleClose = () => {
        props.showChange(false)
      }

      def accountChange = (v: String) => {
        setAccount(v)
      }

      def companyNameChange = (v: String) => {
        setCompanyName(v)
      }

      def passwordChange = (v: String) => {
        setPassword(v)
      }

      def add = () => {
        val index = layer.alert(Tool.myElement, Tool.layerOptions)
        val request = Add.Request(account = account, password = password, companyName = companyName)
        Api.companyMember.add(request).map { xhr =>
          props.refreshTableB().map { x =>
            layer.close(index)
            swal(SwalOptions(title = "成功", text = "新增成功!", `type` = "success"))
            props.showChange(false)
          }
        }
        ()
      }

      def accountValidateF = (v: String) => {
        import shared.pojo.Pojo._
        val request = AccountData(account = v)
        val promise = Promise[Boolean | String]()

        def f = Api.accountCheck(request).map { response =>
          val info = "账号"
          val rs = if (response.valid) {
            true
          } else {
            s"${info}已存在！"
          }
          rs.asInstanceOf[Boolean | String]
        }

        js.timers.clearTimeout(delayTimer)
        val curDelayTimer = js.timers.setTimeout(300) {
          f.map { rs =>
            promise.success(rs)
          }
        }
        setDelayTimer(curDelayTimer)
        promise.future
      }

    }

    Modal(onHide = FTool.handleClose, show = props.show, size = "addModal")(
      Modal.Header(bsPrefix = "modal-header bg-primary", closeButton = true)(
        Modal.Title(
          i(className := "fa fa-plus"),
          span(style := Style(fontWeight = "bold"), id := "lblAddTitle", " 新增")
        )
      ),
      form(id := "form", data - "toggle" := "validator", className := "form-horizontal", onSubmit := {
        useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
          println(JSON.stringify(data))
          FTool.add()
        })
      },
        Modal.Body(
          div(className := "row-fluid",
            InputInlineCp(useForm = useForm, label = "账号", name = "account", labelWidth = 2, inputWidth = 8,
              value = account, onChange = FTool.accountChange, registerOptions = {
                val info = "账号"
                RegisterOptions(
                  required = ValidationValueMessage(value = true, message = s"${info}不能为空！"),
                  validate = FTool.accountValidateF
                )
              }
            ),

            InputInlineCp(useForm = useForm, label = "密码", name = "password", labelWidth = 2, inputWidth = 8, value = password,
              onChange = FTool.passwordChange, registerOptions = RegisterOptions(
                required = ValidationValueMessage(value = true, message = s"密码不能为空！"),
              )),
            InputInlineCp(useForm = useForm, label = "公司名称", name = "companyName", labelWidth = 2, inputWidth = 8, value = companyName,
              onChange = FTool.companyNameChange, registerOptions = RegisterOptions(
                required = ValidationValueMessage(value = true, message = s"公司名称不能为空！"),
              )),
          )
        ),
        Modal.Footer(bsPrefix = "modal-footer bg-info")(
          button(`type` := "submit", className := "btn blue myAdd", "确定"),
          button(`type` := "button", className := "btn green", data - "dismiss" := "modal", "取消",
            onClick := FTool.handleClose),
        )
      )

    )

  }


}
